package com.sn.springboot_netty.utils;

import com.mchange.util.AssertException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author fyy
 * @Dep freemaker word导出工具类
 * @Date 2020/5/13 14:21
 */
public class TemplateWordUtil {

    private static Configuration configuration = null; //模板配置
    private static final String templatePath = TemplateWordUtil.class.getResource("/templates").getPath();
    private static Logger logger = LoggerFactory.getLogger(TemplateWordUtil.class);

    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templatePath));
        } catch (IOException e) {
            logger.error("初始化模板路径出错：{}",e.getMessage());
        }
    }

    /**
     * 文件导出
     * @param dataMap 数据集
     * @param title 文件标题
     * @param ftlPath 模板名称
     */
    public static void exportTemplateWord(HttpServletRequest request, HttpServletResponse response,
                                           Map dataMap,String title,String ftlPath) {
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            Template freemakerTemplate = configuration.getTemplate(ftlPath);

            file = createWord(dataMap,freemakerTemplate);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            String fileName = title + ".doc";
            response.setHeader("Content-Disposition","attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            out = response.getOutputStream();
            byte[] buffer = new byte[2048];  // 缓冲区
            int bytesToRead = -1;
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (IOException e) {
            logger.error("文件导出错误：{}",e.getMessage());
        } finally {
            try {
                if (fin != null) fin.close();
                if (out != null) out.close();
                if (file != null) file.delete();
            } catch (IOException e) {
                logger.error("文件导出流关闭出错：{}",e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
        }


    }

    /**
     * 创建要导出的word文件
     * @param dataMap 数据集
     * @param template 模板
     */
    private static File createWord(Map<?,?> dataMap, Template template) {
        String fileName = "test.doc";
        File file = new File(fileName);
        try {
            Writer writer = new OutputStreamWriter(new FileOutputStream(file),"utf-8");
            template.process(dataMap,writer);
            writer.close();
        } catch (Exception e) {
            logger.error("创建文件出错：{}",e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return file;
    }

    /**
     * 根据图片的路径获取图片的base64码
     * @param imagesPath 图片路径
     */
    public static String getImageBase64(String imagesPath){

        if(StringUtils.isEmpty(imagesPath)){
            return ""; //图片路径为空
        }
        File file = new File(imagesPath);
        if(!file.exists()){
            return ""; //文件不存在
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }


}
